<template>
  <el-card class="card">
    <el-row :gutter="10" class="header">
      <el-col :span="4">
        <el-input placeholder="请输入资产名称..." v-model="queryForm.map.zcmc" clearable></el-input>
      </el-col>
      <el-col :span="4">
        <el-input placeholder="请输入维修流水号..." v-model="queryForm.map.lsh" clearable></el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" :icon="Search" @click="initAssetFixList">搜索</el-button>
      </el-col>
      <el-col :span="12">
        <div style="float: right">
          <el-button :icon="Setting" type="info" @click="showAll">重置</el-button>
          <el-dropdown style="margin: 0 10px 0 10px">
            <el-button type="danger" :icon="Edit">数据操作</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :icon="Edit" @click="handleDialog">添加</el-dropdown-item>
                <el-dropdown-item :icon="Edit" @click="handleUpdate">修改</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-dropdown>
            <el-button :icon="SoldOut" type="success">文件操作</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :icon="SoldOut" @click="handleExcel">导出Excel</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-col>
    </el-row>
    <el-table
            ref="tableDataRef"
            :data="tableData"
            border stripe
            style="width: 100%"
            :cell-style="{textAlign: 'center',lineHeight: '2'}"
            :header-cell-style="{textAlign: 'center'}"
            @selection-change="handleSelectionChange"
            v-loading="loading"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="lsh" label="维修流水号" width="180"/>
      <el-table-column prop="tbrq" label="填报日期" width="130" :formatter="tableRowFormat"/>
      <el-table-column prop="isScrapped" label="是否报废" width="130">
        <template #default="scope">
          <el-tag size="default" v-if="scope.row.isScrapped === 1" type="success" effect="dark">未报废</el-tag>
          <el-tag size="default" v-else-if="scope.row.isScrapped === 2" type="warning" effect="dark">已报废</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="zcbh" label="资产编号" width="115"/>
      <el-table-column prop="zcmc" label="资产名称" width="130"/>
      <el-table-column prop="shsl" label="损坏数量" width="90"/>
      <el-table-column prop="sxrq" label="送修日期" width="130" :formatter="formatDate"/>
      <el-table-column prop="gzyy" label="故障原因" width="130">
        <template #default="scope">
          <span v-if="scope.row.gzyy && scope.row.gzyy.length <= 15">{{ scope.row.gzyy }}</span>
          <el-popover
                  placement="top-start"
                  :content="scope.row.gzyy"
                  v-else-if="scope.row.gzyy && scope.row.gzyy.length>15"
          >
            <template #reference>
              {{ scope.row.gzyy.slice(0, 5) + "..." }}
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="wxzk" label="维修状况" width="130">
        <template #default="scope">
          <span v-if="scope.row.wxzk && scope.row.wxzk.length <= 15">{{ scope.row.wxzk }}</span>
          <el-popover
                  placement="top-start"
                  :content="scope.row.wxzk"
                  v-else-if="scope.row.wxzk && scope.row.wxzk.length>15"
          >
            <template #reference>
              {{ scope.row.wxzk.slice(0, 5) + "..." }}
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="wxfy" label="维修费用" width="100"/>
      <el-table-column label="操作" width="260" fixed="right">
        <template v-slot="scope">
          <el-button type="primary" :icon="List" @click="handleDrawer(scope.row.assetid)">资产信息</el-button>
          <el-button type="info" :icon="Memo" @click="handleInfoDialog(scope.row.id)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
            v-model:current-page="queryForm.pageNum"
            v-model:page-size="queryForm.pageSize"
            :page-sizes="[10,20,20,40,50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
  </el-card>
  <Dialog
          v-model="dialogVisible"
          :dialogVisible="dialogVisible"
          :dialog-title="dialogTitle"
          :id="assetFixId"
          @initAssetFixList="initAssetFixList"
          @clear="clear"
  />
  <InfoDialog
          v-model="InfoDialogVisible"
          :dialogVisible="InfoDialogVisible"
          :id="afid"
  />
  <Drawer v-model="drawerVisible"
          :drawerVisible="drawerVisible"
          :id="aid"
  />
</template>

<script setup>
import { getCurrentInstance, ref } from 'vue'
import request from "@/util/request";
import moment from "moment";
import { Search, Setting, Edit, List, Memo, SoldOut, Document } from '@element-plus/icons-vue';
import Dialog from './components/dialog'
import InfoDialog from './components/infoDialog'
import Drawer from "@/views/page/components/infoDrawer"
import { ElMessage, ElMessageBox } from "element-plus";
import XLSX from "xlsx";
import Excel from "@/util/excelUtil"
import fileSaver from "file-saver"

/**
 * vue3中操作ref实例的写法（proxy代替this）
 */
const {proxy} = getCurrentInstance()

/**
 * 表格数据初始化
 */
const tableData = ref([]);

/**
 * 查询条件
 */
const queryForm = ref({
  map: {
    zcmc: "",
    lsh: "",
  },
  pageNum: 1,
  pageSize: 10,
})

/**
 * 数据总数
 */
const total = ref(0);

const loading = ref(true)

/**
 * 获取资产设别损坏数据
 */
const initAssetFixList = async () => {
  const res = await request.post("assetFix/list", queryForm.value);
  if (res.data.code === 200) {
    loading.value = false;
    tableData.value = res.data.assetFixList;
    total.value = res.data.total;
  }
}
initAssetFixList();

/**
 * 搜索条件重置
 */
const showAll = () => {
  queryForm.value.query = '';
  initAssetFixList();
  clear();
}

/**
 * 清楚状态
 */
const clear = () => {
  ids.value = [];
  assetFixId.value = -1;
  proxy.$refs.tableDataRef.clearSelection();
}

/**
 * 处理每页记录数变化
 * @param pageSize
 */
const handleSizeChange = (pageSize) => {
  queryForm.value.pageNum = 1;
  queryForm.value.pageSize = pageSize;
  initAssetFixList();
}

/**
 * 处理第几页变化
 * @param pageNum
 */
const handleCurrentChange = (pageNum) => {
  queryForm.value.pageNum = pageNum;
  initAssetFixList();
}

/**
 * 表格通用格式化时间信息
 * @param row
 * @param column
 * @returns {string}
 */
const formatDate = (row, column) => {
  let date = row[column.property];
  if (date === undefined) {
    return "";
  }
  return moment(date).format("YYYY/MM/DD");
}

/**
 * 通用格式化时间信息
 * @param data
 * @returns {string}
 */
const currencyFormatDate = (data) => {
  let date = data;
  if (date === undefined) {
    return "";
  }
  return moment(date).format("YYYY-MM-DD");
}

const tableRowFormat = (row, column, cellValue) => {
  return cellValue == null ? "--" : currencyFormatDate(cellValue);
}

const ids = ref([]) //表格选中数据的id集合

/**
 * 表格选中方法
 */
const handleSelectionChange = (selection) => {
  if (selection.length >= 1) {
    ids.value = selection;
  } else {
    ids.value = [];
  }
}

const dialogVisible = ref(false); //dialog显示
const dialogTitle = ref(""); //dialog标题
const assetFixId = ref(-1); //损毁资产的id

const openDialog = () => {
  dialogVisible.value = true;
  dialogTitle.value = "资产设备维修填报"
}

/**
 * 打开dialog
 */
const handleDialog = () => {
  if (ids.value.length === 0) {
    console.log(assetFixId.value)
    openDialog();
  } else {
    ElMessageBox.confirm(
            "当前已选中数据，确认进行增加信息吗？",
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
            .then(async () => {
              clear();
              openDialog();
            })
            .catch(() => {
              clear();
            })
  }
}

const handleUpdate = () => {
  if (ids.value.length === 1) {
    ids.value.forEach((item) => {
      assetFixId.value = item.id;
    })
    console.log(assetFixId.value)
    openDialog();
  } else if (ids.value.length === 0) {
    ElMessage.error("请选择数据")
  } else if (ids.value.length > 1) {
    ElMessage.error("请选择一条数据")
  }
}

const drawerVisible = ref(false); //dialog显示
const aid = ref(-1); //损毁资产的id

const handleDrawer = (id) => {
  aid.value = id;
  drawerVisible.value = true;
}

const InfoDialogVisible = ref(false); //dialog显示
const afid = ref(-1); //损毁资产的id
const handleInfoDialog = (id) => {
  afid.value = id;
  InfoDialogVisible.value = true;
}

/**
 * 导出excel方法
 */
const exportExcel = (list) => {
  //自定义表头
  let data = [["基本信息状态表"], []];
  data.push([
    '维修流水号', '填报日期', '是否报废',
    '资产编号', '资产名称', '损坏数量',
    '送修日期', "故障原因", "维修状况", "维修费用"
  ]);
  //参数遍历添加内容
  list.forEach((item) => {
    let rowData = []
    //导出内容的字段
    rowData = [
      item.lsh,
      currencyFormatDate(item.tbrq),
      item.isScrapped === 1 ? "未报废" : "已报废",
      item.zcbh,
      item.zcmc,
      item.shsl,
      currencyFormatDate(item.sxrq),
      item.gzyy,
      item.wxzk,
      item.wxfy,
    ]
    data.push(rowData)
  })
  const sheet = excelStyle(data);
  const sheetToBlob = Excel.sheetToBlob(sheet, "工作簿");
  Excel.downLoadExcel(sheetToBlob, "资产设备维修（损坏）信息表.xlsx")
}

/**
 * 自定义excel样式
 */
const excelStyle = (data) => {
  const ws = XLSX.utils.aoa_to_sheet(data);
  // 合并的单元格
  const mergeArr = [];
  // 表格每列高度
  const rowH = [];
  // 单元格外侧有框线
  const borderAll = {
    top: {style: "thin"},
    bottom: {style: "thin"},
    left: {style: "thin"},
    right: {style: "thin"},
  };
  // 单元格外侧无框线
  const noBorder = {
    top: {style: ""},
    bottom: {style: ""},
    left: {style: ""},
    right: {style: ""},
  };
  for (const key in ws) {
    if (Object.hasOwnProperty.call(ws, key)) {
      const element = ws[key];
      if (typeof element === "object") {
        let index = Number(key.slice(1)) - 1;
        rowH[index] = {wpx: 50};
        // console.log(index)
        element.s = {
          alignment: {
            //所有单元格右对齐
            horizontal: "left",
            //所有单元格垂直居中
            vertical: "center",
          },
          border: borderAll,
          font: {
            name: "宋体", //字体
            sz: 11,
            italic: false,
            underline: false,
          },
        };
        // 表格标题的样式
        if (index === 2) {
          element.s.font.bold = true;
          element.s.font.sz = 14;
        }
        // 处理合并单元格数组 s 开始 e 结束  c 列 r行
        if (element.v === "基本信息状态表") {
          mergeArr.push({
            s: {c: 0, r: 0},
            e: {c: 9, r: 1},
          });
        }
      }
    }
  }
  //表头的样式设置
  ws["A1"].s = {
    alignment: {
      horizontal: "center",
      vertical: "center",
    },
    font: {
      name: "宋体",
      sz: 20,
      italic: false,
      underline: false,
      bold: true,
      color: {rgb: 'FFFFFF'}
    },
    border: noBorder,
    fill: {
      fgColor: {rgb: "ff3333"},
    },
  }
  //单元格的列宽
  ws["!cols"] = [
    {wpx: 120}, {wpx: 120}, {wpx: 120}, {wpx: 120}, {wpx: 120},
    {wpx: 120}, {wpx: 120}, {wpx: 120}, {wpx: 120}, {wpx: 120}
  ];
  ws["!rows"] = rowH;
  //合并的单元格
  ws["!merges"] = mergeArr;
  return ws;
}

//excel基本变量
const exportVariable = ref({
  title: "确认导出全部数据吗",
  idArray: [],
  dataList: [],
})

//重置excel基本变量
const resetExportVariable = () => {
  exportVariable.value.title = "确认导出全部的数据吗";
  exportVariable.value.idArray = [];
  exportVariable.value.dataList = [];
}

/**
 * 表格数据导出Excel调用方法
 */
const handleExcel = async () => {
  //首先判断导出全部数据还是导出选中的数据
  //如果定义选中数据的id数组不为空执行如下的if语句重新赋值
  if (ids.value.length !== 0) {
    ids.value.forEach((item) => {
      exportVariable.value.idArray.push(item.id)
    })
    //改变提示信息
    exportVariable.value.title = "确认导出选中的数据吗"
    //根据id数组查询数据
    const res = await request.post("assetFix/listById", exportVariable.value.idArray);
    //赋值给传参数组
    exportVariable.value.dataList = res.data.assetFixList;
  }
  ElMessageBox.confirm(
          exportVariable.value.title,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
          .then(async () => {
            //判断传参数组是否为空
            if (exportVariable.value.dataList.length === 0) {
              //为空导出全部数据
              exportExcel(tableData.value);

            } else {
              //不为空导出选中的数据
              exportExcel(exportVariable.value.dataList);
              resetExportVariable();
            }
            ElMessage.success("导出成功")
          })
          .catch(() => {
            //消息提示框点击取消或者关闭重置导出excel基本变量
            resetExportVariable();
          })
}
</script>

<style lang="scss" scoped>
.header {
  margin-bottom: 15px;
}

.el-pagination {
  float: right;
  padding: 20px;
  box-sizing: border-box;
}

::v-deep th.el-table__cell {
  word-break: break-word;
  background-color: #f8f8f9 !important;
  color: #515a6e;
  height: 40px;
  font-size: 15px;
}

.el-tag--small {
  margin-left: 5px;
}

.card {
  border: none;
  border-radius: 0;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.bottom {
  margin-bottom: 10px;
}

.card-header {
  display: flex;
  align-items: center;
}

.icon_size {
  color: #565656;
}

.header_info {
  font-weight: bolder;
  font-size: 15px;
  margin-left: 5px;
}

.title_info {
  margin: 0 0 10px 30px;
  font-size: 15px;
}
</style>